﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCBugTracker.Models;
using MVCBugTracker.ViewModels;

namespace MVCBugTracker.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        public IProfileRepository ProfileRepository { get; set; }
        public IProjectRepository ProjectRepository { get; set;}

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            if (ProfileRepository == null) { ProfileRepository = new EFProfileRepository(); }
            if (ProjectRepository == null) { ProjectRepository = new EFProjectRepository(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            if (User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Bug", null);

            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        int? defaultProjectID = ProfileRepository.GetProfile(model.UserName).DefaultProjectID;
                            
                        return RedirectToAction("Index", "Bug", new { projectID = defaultProjectID });
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("LogOn", "Account");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
                UserProfile profile = new UserProfile() { UserName = model.UserName, FullName = model.FullName };
                ProfileRepository.AddProfile(profile);
                ProfileRepository.Save();

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false);
                    return RedirectToAction("Index", "Bug", null);
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // **************************************
        // URL: /Account/Profile
        // **************************************
        public ActionResult Profile()
        {
            var results = new AccountProfileViewModel();
            results.UsersProjects = ProjectRepository.GetMyProjects(User.Identity.Name).ToList();
            results.Profile = ProfileRepository.GetProfile(User.Identity.Name);

            return View(results);
        }

        [HttpPost]
        public ActionResult Profile(FormCollection collection)
        {
            UserProfile profile = ProfileRepository.GetProfile(User.Identity.Name);
            profile.FullName = collection["Profile.FullName"];
            if (collection["Profile.DefaultProjectID"] != null)
                profile.DefaultProjectID = int.Parse(collection["Profile.DefaultProjectID"]);
            ProfileRepository.Save();

            var results = new AccountProfileViewModel();
            results.UsersProjects = ProjectRepository.GetMyProjects(User.Identity.Name).ToList();
            results.Profile = profile;
            results.Message = "Profile Saved.";

            return View(results);
        }
    }
}
